package com.zhiyume.api.controller;

import com.zhiyume.api.util.ApiConstants;
import com.zhiyume.api.util.ApiOperateEnum;
import com.zhiyume.api.vo.PersonReq;
import com.zhiyume.dao.api.TDramaPersonMapper;
import com.zhiyume.dao.api.TPersonMapper;
import com.zhiyume.dao.api.TPersonSelfMapper;
import com.zhiyume.dao.entity.*;
import com.zhiyume.page.PageReq;
import com.zhiyume.page.Pager;
import com.zhiyume.service.common.ConstantEnum;
import com.zhiyume.service.util.DateUtil;
import com.zhiyume.service.util.JsonUtil;
import com.zhiyume.service.util.StringUtil;
import com.zhiyume.util.TypeConstants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 * @description 演员关请求接口
 */
@RestController
@RequestMapping("/api/actor")
@Api(tags = "演员关请求接口")
public class ActorAction {

    @Autowired
    private TPersonMapper tPersonMapper;


    @Autowired
    private TPersonSelfMapper tPersonSelfMapper;

    @Autowired
    private TDramaPersonMapper tDramaPersonMapper;

    private String successType = ConstantEnum.CONSTANT_SUCCESS.getErrType();
    private String successMsg = ConstantEnum.CONSTANT_SUCCESS.getErrMsg();

    private static final Log log = LogFactory.getLog(ActorAction.class.getName());
    private static final String MODULE = ActorAction.class.getName();
    /**
     * 根据id获取actor
     * @param id
     * @return
     */
    @GetMapping("/findActorById")
    @ApiIgnore
    @ResponseBody
    public Map findActorById(@RequestParam(defaultValue = "") String id){
        TPerson tActor = null;
        Map result = new HashMap();
        if(StringUtil.isBlank(String.valueOf(id))){
            result = JsonUtil.returnResult(ConstantEnum.CONSTANT_MISS_PARA.getErrType(),ConstantEnum.CONSTANT_MISS_PARA.getErrMsg());
        }else if(!StringUtil.isNumeric(String.valueOf(id))){
            result =JsonUtil.returnResult(ConstantEnum.CONSTANT_PARA_ERROR.getErrType(),ConstantEnum.CONSTANT_PARA_ERROR.getErrMsg());
        }else {
//            tActor = iActorService.findActorById(Long.parseLong(id));
            if(tActor == null){
                result =JsonUtil.returnResult(ConstantEnum.CONSTANT_NO_DATA.getErrType(),ConstantEnum.CONSTANT_NO_DATA.getErrMsg());
            }else{
                result = JsonUtil.returnResult(successType,successMsg,tActor);
            }
        }
        return result;
    }

    /**
     * 根据剧名获取剧列表
     * @param name
     * @return
     */
    @GetMapping("/findActorListByName")
    @ApiIgnore
    public Object findActorListByName(@RequestParam(defaultValue = "") String name){
        List<TPerson> tActorList = new ArrayList<>();
        Map result = new HashMap();
        if(StringUtil.isBlank(String.valueOf(name))){
            result = JsonUtil.returnResult(ConstantEnum.CONSTANT_MISS_PARA.getErrType(),ConstantEnum.CONSTANT_MISS_PARA.getErrMsg());
        }else {
//            tActorList = iActorService.findActorsListByName(name);
            if(tActorList == null || tActorList.size() < 1){
                result =JsonUtil.returnResult(ConstantEnum.CONSTANT_NO_DATA.getErrType(),ConstantEnum.CONSTANT_NO_DATA.getErrMsg());
            }else{
                result = JsonUtil.returnResult(successType,successMsg,tActorList);
            }
        }
        return result;
    }

    /**
     * 根据导演获取剧列表
     * @param director
     * @return
     */
    @GetMapping("/findActorListByDirector")
    @ApiIgnore
    public Object findActorListByDirector(@RequestParam(defaultValue = "") String director){
        List<TPerson> tActorList = new ArrayList<>();
        Map result = new HashMap();
        if(StringUtil.isBlank(String.valueOf(director))){
            result = JsonUtil.returnResult(ConstantEnum.CONSTANT_MISS_PARA.getErrType(),ConstantEnum.CONSTANT_MISS_PARA.getErrMsg());
        }else {
//            tActorList = iActorService.findActorsListByDirector(director);
            if(tActorList == null || tActorList.size() < 1){
                result =JsonUtil.returnResult(ConstantEnum.CONSTANT_NO_DATA.getErrType(),ConstantEnum.CONSTANT_NO_DATA.getErrMsg());
            }else{
                result = JsonUtil.returnResult(successType,successMsg,tActorList);
            }
        }
        return result;
    }

    /**
     * 根据剧类别获取剧列表
     */
    @GetMapping("/findActorListByType")
    @ApiIgnore
    public Object findActorListByType(@RequestParam(defaultValue = "") String actorType,
                                      @RequestParam(defaultValue = "0") int page,
                                      @RequestParam(defaultValue = "10") int pageSize){
        List<TPerson> tActorList = new ArrayList<>();
        Map result = new HashMap();
        if(StringUtil.isBlank(String.valueOf(actorType))){
            result = JsonUtil.returnResult(ConstantEnum.CONSTANT_MISS_PARA.getErrType(),ConstantEnum.CONSTANT_MISS_PARA.getErrMsg());
        }else if(!StringUtil.isNumeric(actorType)){
            result =JsonUtil.returnResult(ConstantEnum.CONSTANT_PARA_ERROR.getErrType(),ConstantEnum.CONSTANT_PARA_ERROR.getErrMsg());
        }else {
//            tActorList = iActorService.findActorsListByType( page, pageSize, actorType);
            if(tActorList == null || tActorList.size() < 1){
                result =JsonUtil.returnResult(ConstantEnum.CONSTANT_NO_DATA.getErrType(),ConstantEnum.CONSTANT_NO_DATA.getErrMsg());
            }else{
                result = JsonUtil.returnResult(successType,successMsg,tActorList);
            }
        }
        return result;
    }


    /**
     * 根据出品公司获取剧列表
     */
    @GetMapping("/findActorListByCompany")
    @ApiIgnore
    @ResponseBody
    public Map findActorListByCompany(@RequestParam(defaultValue = "") String company){
        List<TPerson> tActorList = new ArrayList<>();
        Map result = new HashedMap();
        if(StringUtil.isBlank(String.valueOf(company))){
            result = JsonUtil.returnResult(ConstantEnum.CONSTANT_MISS_PARA.getErrType(),ConstantEnum.CONSTANT_MISS_PARA.getErrMsg());
        }else {
//            tActorList = iActorService.findActorListByCompany(company);
            if(tActorList == null || tActorList.size() < 1){
                result =JsonUtil.returnResult(ConstantEnum.CONSTANT_NO_DATA.getErrType(),ConstantEnum.CONSTANT_NO_DATA.getErrMsg());
            }else{
                result = JsonUtil.returnResult(successType,successMsg,tActorList);
            }
        }
        return result;
    }


    @RequestMapping(value="/list", method={RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "查询演员")
    @ResponseBody
    public Map queryActors(PersonReq page){
        Pager p = null;
        try{
            if(page.getPageSize() > ApiConstants.MAX_NUM)
                throw new Exception("超过最大值");
            p = getActorSearchPager(page);
            return JsonUtil.returnResult(successType,successMsg,p);
        }catch (Exception e){
            log.error(MODULE,e);
            return JsonUtil.returnResult(ConstantEnum.CONSTANT_SYS_ERROR.getErrType(),ConstantEnum.CONSTANT_SYS_ERROR.getErrMsg());
        }
    }

    private Pager getActorPager(PageReq pageVO){
        List<Integer> actor = new ArrayList<Integer>(){{
            add(1);
        }};
        return getPersonPager(pageVO,actor);
    }


    private Pager getActorSearchPager(PersonReq pageVO){
        List<Integer> actor = new ArrayList<Integer>(){{
            add(TypeConstants.PersonConstant.PERSON_ACTOR);
        }};
        return getPersonSearchPager(pageVO,actor);
    }

    /**
     * @param page
     * @return
     */
    private Pager getPersonPager(PageReq page, List<Integer> types){
        Pager p = new Pager();

        TPersonCriteria total = new TPersonCriteria();
        TPersonCriteria.Criteria total_c = total.createCriteria();

        //分别拆开，注意对象的对应关

        total_c.andCareerIn(types);
        orderAndSetId(page, total, total_c);


        p.setTotalCount(tPersonMapper.countByExample(total));
        //翻页
        total.setLimitStart(0);
        total.setLimitEnd(page.getPageSize());


        List<TPersonWithBLOBs> ts = new ArrayList<>();

        ts = tPersonMapper.selectByExampleWithBLOBs(total);
        List datas =loadData(ts);

        p.setPageSize(page.getPageSize());

        p.setItems(datas);
        return p;
    }

    /**
     * @param page
     * @return
     */
    private Pager getPersonSearchPager(PersonReq page, List<Integer> types){
        Pager p = new Pager();

        TPersonCriteria total = new TPersonCriteria();
        TPersonCriteria.Criteria total_c = total.createCriteria();

        TPersonCriteria total_des = new TPersonCriteria();
        TPersonCriteria.Criteria total_des_c = total_des.createCriteria();


        //分别拆开，注意对象的对应关

        if(-1!=page.getGender()){
            total_c.andGenderEqualTo(page.getGender());
        }
        if(-1!=page.getHeight()){
            total_c.andHeightEqualTo(page.getHeight());
        }

        if(null!=page.getBirthBegin()){
            total_c.andBirthGreaterThanOrEqualTo(DateUtil.shortDate(page.getBirthBegin()));
        }
        if(null!=page.getBirthEnd()){
            total_c.andBirthLessThanOrEqualTo(DateUtil.shortDate(page.getBirthEnd()));
        }
        if(StringUtil.isNotBlank(page.getTitle())){
            total_c.andNameLike("%"+page.getTitle()+"%");
            total_des_c.andRepWorksLike("%"+page.getTitle()+"%");

        }
        total_c.andCareerIn(types);
        orderAndSetId(page, total, total_c);

        total.or(total_des_c);
        p.setTotalCount(tPersonMapper.countByExample(total));
        //翻页
        total.setLimitStart(0);
        total.setLimitEnd(page.getPageSize());


        List<TPersonWithBLOBs> ts = new ArrayList<>();

        ts = tPersonSelfMapper.selectByMyExample(total);
        List datas =loadData(ts);

        p.setPageSize(page.getPageSize());

        p.setItems(datas);
        return p;
    }

    private void orderAndSetId(PageReq page, TPersonCriteria total, TPersonCriteria.Criteria total_c) {
        if(ApiOperateEnum.UP.getName().equals(page.getHandle())){
            total_c.andIdGreaterThan(page.getDataId());
            total.setOrderByClause("id asc,`t_id` asc");
        }
        else if(ApiOperateEnum.DOWN.getName().equals(page.getHandle())){
            total_c.andIdLessThan(page.getDataId());
            total.setOrderByClause("id desc,`t_id` desc");
        }else if(ApiOperateEnum.REFRESH.getName().equals(page.getHandle())){
            total.setOrderByClause("id desc,`t_id` desc");
        }else{
            total.setOrderByClause("id desc,`t_id` desc");
        }
    }

    private List loadData(List<TPersonWithBLOBs> persons) {
        List list = new ArrayList();

        for(TPersonWithBLOBs person:persons){
            Map temp = new HashMap();
            String imgUrl = person.getFaceurl();
            temp.put("dataId",person.getId());
            temp.put("faceUrl",imgUrl);
            temp.put("description",person.getDescription());
            String repWorks = buildRepWorks(person.getId());
            temp.put("repWorks",repWorks);
            temp.put("gender",person.getGender()==1?"女":"男");
            temp.put("dataId",person.getId());
            temp.put("birth",person.getBirth());
            temp.put("link",person.getId());
            temp.put("name",person.getName());
            list.add(temp);
        }
        return list;
    }

    //根据用户找代表作品
    private String buildRepWorks(Long personId){

        StringBuilder repWorks = new StringBuilder();
        TDramaPersonCriteria t = new TDramaPersonCriteria();
        TDramaPersonCriteria.Criteria c = t.createCriteria();
        c.andPIdEqualTo(personId);
        t.setLimitStart(0);
        t.setLimitEnd(10);
        List<TDramaPerson> reps =tDramaPersonMapper.selectByExample(t);

        if(CollectionUtils.isEmpty(reps)){
            return "";
        }else{
            int isEnd = 0;
            for(TDramaPerson tp:reps){
                repWorks.append("《" + tp.getDramaName() + "》");
                isEnd ++;
                if(isEnd != reps.size()){
                    repWorks.append( "、");
                }
            }
            return repWorks.toString();
        }
    }

}
